﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using CustomerServiceCenter.Models;
using BusinessLayer;
using BusinessLayer.VDataEntities;
using System.Web.Http;
using System.IO;
using System.Collections;
using BusinessLayer.DatabaseEntities;
using System.Web.Script.Serialization;
using CustomerServiceCenter.Helper;
using System.Configuration;
using System.Drawing.Imaging;
using System.Drawing;
using System.Drawing.Drawing2D;
namespace CustomerServiceCenter.Controllers.API
{
    public class WeChatController : ApiController
    {
        public static List<string> imagesPath = new List<string>();
        //查看某一请求当前的处理日志
        public OperationLogModel[] GetTicketsLogs()
        {
            string ticketID = HttpContext.Current.Request.QueryString["ticketID"];
            TicketOperationLog[] logs = BusinessLayer.TicketBusiness.GetTicketOperationLog(long.Parse(ticketID));
            List<OperationLogModel> operationLogs = new List<OperationLogModel>();
            foreach (TicketOperationLog log in logs)
            {
                OperationLogModel olm = new OperationLogModel();
                olm.OperationName = EnumDescripte.GetEnumDeScription((TicketStatusType)log.Operation);
                olm.OperationTime = string.Format("{0:yyyy-MM-dd hh:mm}", log.OperationTime);
                operationLogs.Add(olm);
            }
            if (operationLogs.Count > 0)
            {
                return operationLogs.ToArray();
            }
            else
            {
                return null;
            }
        }
        //根据状态获取用户的tickets
        public static List<TicketWeiXinModel> GetTickets(long EndUserID, int TicketStatus = 0, int ticketid = -1)
        {
            VTicketEntity[] tickets = BusinessLayer.TicketBusiness.GetTickets(EndUserID, TicketStatus, ticketid);

            List<TicketWeiXinModel> ticketsModel = new List<TicketWeiXinModel>();
            foreach (VTicketEntity ticket in tickets)
            {
                TicketWeiXinModel twxm = new TicketWeiXinModel();
                twxm.AssignerName = ticket.AssignerInfo.Name;
                twxm.AssignDate = ticket.AssignDate;
                twxm.ClientID = ticket.User.ClientID;
                twxm.IssueDescription = ticket.IssueDescription;
                twxm.IssueType = ProjectBusiness.GetIssueTypeInfoBySome(Convert.ToInt32(ticket.IssueType)).FirstOrDefault().IssueTypeDescription;
                twxm.Mobile = ticket.AssignerInfo.Mobile;
                twxm.OrderNumber = ticket.OrderNumber;
                twxm.Status = EnumDescripte.GetEnumDeScription((ShortStatus)ticket.Status);
                twxm.SubmitDate = ticket.SubmitDate;
                twxm.Telephone = ticket.AssignerInfo.Telephone;
                twxm.Email = ticket.AssignerInfo.Email;
                twxm.TicketID = ticket.TicketID;
                long[] applicationID = new long[] { ticket.ApplicationID };
                List<VApplication> applicationInfo = ProjectBusiness.GetApplicationInfoById(applicationID);
                if (null != applicationInfo && applicationInfo.Count > 0)
                {
                    twxm.OnCall = applicationInfo[0].OnCall;
                }
                ticketsModel.Add(twxm);
            }

            return ticketsModel;
        }

        //用户提醒工程师处理
        [System.Web.Http.HttpGet]
        public string RemindOperator(string toAddress, string ticketID)
        {
            //string toAddress = HttpContext.Current.Request.QueryString["toAddress"];
            string remind_message = ConfigurationManager.AppSettings["message"].ToString();
            long time = long.Parse(ConfigurationManager.AppSettings["maxTime"].ToString());
            string ToAddress = ConfigurationManager.AppSettings["ToAddress"].ToString();
            if (!string.IsNullOrWhiteSpace(toAddress) && toAddress != "")
            {
                //已经有工程师接受
                remind_message = remind_message + ticketID + ConfigurationManager.AppSettings["OperMSG"];
                EmailInfo infomation = new EmailInfo { toEmailAddress = toAddress, info = remind_message };
                //若已经提醒过了
                if (HttpContext.Current.Session["timer"] != null)
                {
                    string timer = HttpContext.Current.Session["timer"].ToString();
                    DateTime hadTime = Convert.ToDateTime(timer).AddHours(time);
                    //若已经过的时间加上提醒间隔大于当前时间的话
                    if (string.IsNullOrWhiteSpace(timer) && hadTime >= DateTime.Now)
                    {
                        CEmail.sendEmailFunction(infomation);
                        return "成功提醒工程师," + CEmail.PCEmailReturnMassage;
                    }
                    else
                    {
                        return "你已提醒过工程师了，请过段时间再来吧";
                    }
                }
                //还没有提醒过，第一次提醒
                else
                {
                    HttpContext.Current.Session.Add("timer", DateTime.Now);
                    CEmail.sendEmailFunction(infomation);
                    return "成功提醒工程师," + CEmail.PCEmailReturnMassage;
                }
            }
            else
            {
                //还没有工程师
                remind_message = remind_message + ticketID + ConfigurationManager.AppSettings["NoOperMSG"];
                EmailInfo infomation = new EmailInfo { toEmailAddress = ToAddress, info = remind_message };
                //若已经提醒过了
                if (HttpContext.Current.Session["NoOpertimer"] != null)
                {
                    string timer = HttpContext.Current.Session["NoOpertimer"].ToString();
                    DateTime hadTime = Convert.ToDateTime(timer).AddHours(time);
                    //若已经过的时间加上提醒间隔大于当前时间的话
                    if (string.IsNullOrWhiteSpace(timer) && hadTime >= DateTime.Now)
                    {

                        CEmail.sendEmailFunction(infomation);
                        return "成功提醒工程师," + CEmail.PCEmailReturnMassage;
                    }
                    else
                    {
                        return "你已提醒过工程师了，请过段时间再来吧";
                    }
                }
                //还没有提醒过，第一次提醒
                else
                {
                    HttpContext.Current.Session.Add("NoOpertimer", DateTime.Now);
                    CEmail.sendEmailFunction(infomation);
                    return "成功提醒工程师," + CEmail.PCEmailReturnMassage;
                }
            }
        }

        #region 图片高质量压缩
        /// <summary>
        /// 图片压缩 
        /// </summary>
        /// <param name="sourceImg"></param>
        /// <param name="outPath">保存路径</param>
        /// <param name="flag">压缩比例</param>
        /// <returns></returns>
        public static bool GetPicThumbnail(System.Drawing.Image sourceImg, string outPath, int flag)
        {
            System.Drawing.Image iSource = sourceImg;
            ImageFormat tFormat = iSource.RawFormat;

            //以下代码为保存图片时，设置压缩质量  
            EncoderParameters ep = new EncoderParameters();
            long[] qy = new long[1];
            qy[0] = flag;//设置压缩的比例1-100  
            EncoderParameter eParam = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, qy);
            ep.Param[0] = eParam;
            try
            {
                ImageCodecInfo[] arrayICI = ImageCodecInfo.GetImageEncoders();
                ImageCodecInfo jpegICIinfo = null;
                for (int x = 0; x < arrayICI.Length; x++)
                {
                    if (arrayICI[x].FormatDescription.Equals("JPEG"))
                    {
                        jpegICIinfo = arrayICI[x];
                        break;
                    }
                }
                if (jpegICIinfo != null)
                {
                    iSource.Save(outPath, jpegICIinfo, ep);//dFile是压缩后的新路径  
                }
                else
                {
                    iSource.Save(outPath, tFormat);
                }
                return true;
            }
            catch
            {
                return false;
            }
            finally
            {
                iSource.Dispose();
                iSource.Dispose();
            }
        }
        #endregion 结束

        public List<IssueTypePCModel> GetIssueTypeInfo()
        {
            //string EndUserName = UserHelper.GetCurrentPromoterUser().ChineseName;
            //var endUserInfo  = AdminBusiness.GetEndUserInfo(EndUserName);
            long[] applicationID = ProjectBusiness.GetApplicationIDByClientID(UserHelper.GetCurrentPromoterUser().ClientID);
            List<IssueType> IssueTypeList = ProjectBusiness.GetIssueType(applicationID);
            List<IssueTypePCModel> list = new List<IssueTypePCModel>();
            foreach (var item in IssueTypeList)
            {
                IssueTypePCModel issueType = new IssueTypePCModel();
                issueType.ApplicationID = item.ApplicationID;
                issueType.ID = item.ID;
                issueType.IssueTypeDescription = item.IssueTypeDescription;
                issueType.IsActive = item.IsActive;
                issueType.Type = item.Type;
                list.Add(issueType);
            }
            return list;
        }


        //public RequestModel GetLastTicketDetailByEndUserID()
        //{

        //    VTicketRequest tickets = BusinessLayer.TicketBusiness.GetTicketsBySome(UserHelper.GetCurrentPromoterUser().ID);
        //    RequestModel ticketsModel = new RequestModel();
        //    if (tickets != null)
        //    {
        //        ticketsModel.ApplicationUserName = tickets.ApplicationUserName;
        //    }
        //    return ticketsModel;
        //}

        [System.Web.Http.HttpPost]
        public string SaveImageAndReturnImageName()
        {
            try
            {
                HttpPostedFile file;
                HttpFileCollection col;
                if (HttpContext.Current.Request.Files != null && HttpContext.Current.Request.Files.Count > 0)
                {
                    DateTime time = DateTime.Now;
                    col = HttpContext.Current.Request.Files;
                    for (int i = 0; i < col.Count; i++)
                    {
                        file = col[i];
                        string name = file.FileName;

                        if (file != null && file.ContentLength != 0 && !string.IsNullOrEmpty(file.FileName))
                        {

                            //string format = "." + file.FileName.Split('.')[file.FileName.Split('.').Length - 1];
                            TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0);   //时间戳  
                            string filename = Convert.ToInt64(ts.TotalSeconds).ToString();     //图片名  
                            long EnduserID = UserHelper.GetCurrentPromoterUser().ID;
                            if (!Directory.Exists(HttpContext.Current.Server.MapPath("~/content/Resources/images/Enterprise/" + EnduserID + "/")))
                            {
                                Directory.CreateDirectory(HttpContext.Current.Server.MapPath("~/content/Resources/images/Enterprise/" + EnduserID + "/"));
                            }
                            file.SaveAs(HttpContext.Current.Server.MapPath("~/content/Resources/images/Enterprise/" + EnduserID + "/") + filename + "-" + name);
                            if (null != imagesPath && imagesPath.Count > 0)
                            {
                                string EnduserIDString = UserHelper.GetCurrentPromoterUser().ID.ToString();
                                for (int j = 0; j < imagesPath.Count; j++)
                                {
                                    string[] paths = imagesPath[j].Split('/');
                                    if (paths.Contains(EnduserIDString) && imagesPath[j].Split('-')[1].Equals(name))
                                    {
                                        imagesPath.Remove(imagesPath[j]);
                                    }
                                }
                            }
                            imagesPath.Add("/content/Resources/images/Enterprise/" + EnduserID + "/" + filename + "-" + name);
                            return null;

                        }
                    }
                }

            }
            catch (Exception)
            {
                return "imageError";
                throw;
            }
            return null;
        }


        #region 添加申请
        public string AddTickets(RequestModel model)
        {
            try
            {
                List<VTicketInputFieldData> inputFieldData = new List<VTicketInputFieldData>();

                foreach (var data in model.InputDataValue)
                {
                    if (data.Id == 0) continue;
                    VTicketInputFieldData fieldData = new VTicketInputFieldData()
                    {
                        TicketInputFieldID = data.Id,
                        Value = data.Value,
                    };
                    inputFieldData.Add(fieldData);
                }

                VTicketRequest ticket = new VTicketRequest
                {
                    ApplicationID = model.ApplicationID,
                    ApplicationUserName = UserHelper.GetCurrentPromoterUser().ChineseName,
                    EndUserId = UserHelper.GetCurrentPromoterUser().ID,
                    //ApplicationUserName = "test",
                    //EndUserId = 1,
                    IssueDescription = model.IssueDescription,
                    Status = Convert.ToInt32(TicketStatusType.New),
                    IsFromWeChat = 1,
                    FieldData = inputFieldData,
                    IsActive = true,
                    Email = model.Email,
                    Mobile = model.Mobile
                };
                if (model.IssueType != 0) ticket.IssueType = model.IssueType;
                if (model.Priority != 0)
                {
                    ticket.Priority = model.Priority;
                }
                else
                {
                    ticket.Priority = Convert.ToInt32(TicketPrrority.medium);
                }
                //List<String> imagesList = imagesPath;
                List<String> imagesList = CustomerServiceCenter.Controllers.API.WeChatController.imagesPath;
                string[] images = new string[imagesList.Count];
                string EnduserID = UserHelper.GetCurrentPromoterUser().ID.ToString();
                //string EnduserID = "1";
                int item = 0;
                bool flag = false;
                if (null != imagesList && imagesList.Count > 0)
                {
                    for (int i = 0; i < imagesList.Count; i++)
                    {
                        string[] paths = imagesList[i].Split('/');
                        if (paths.Contains(EnduserID))
                        {
                            flag = true;
                        }
                        if (flag)
                        {
                            images[item] = imagesList[i];
                            LogHelper.Info(UserHelper.GetCurrentPromoterUser().ChineseName + "add" + images[item]);
                            item++;
                            flag = false;
                        }
                    }
                }
                ApplicationBusiness.AddTicket(ticket, images, Convert.ToInt32(TicketStatusType.New));
                LogHelper.Info(UserHelper.GetCurrentPromoterUser().ChineseName + "创建了ticket请求");
                return null;
            }
            catch (Exception e)
            {
                //throw e;
                return "添加失败";
            }
        }


        #endregion 添加申请结束



        #region  GetInputFieldInfo
        [System.Web.Http.HttpGet]
        public List<InputFieldAndDataSource> GetInputFieldAndDataSourceInfo(int applicationId,int issueTypeId =0)
        {
            List<InputFieldAndDataSource> inputFieldAndDataSourceList = new List<InputFieldAndDataSource>();
            List<VTicketInputField> field = TicketBusiness.GetTicketInputFieldBySome(applicationId,issueTypeId);
            //VTicketInputField 

            if (field == null || field.Count <= 0) return inputFieldAndDataSourceList;
            foreach (var inputField in field)
            {

                InputFieldAndDataSource fieldAndDataSource = new InputFieldAndDataSource();
                fieldAndDataSource.FieldID = inputField.Id;
                fieldAndDataSource.FieldDataType = inputField.DataType;
                fieldAndDataSource.FieldDescription = inputField.Description;
                fieldAndDataSource.FieldName = inputField.Name;
                fieldAndDataSource.FieldSortSeq = inputField.SortSeq;
                fieldAndDataSource.IssueTypeID = inputField.IssueTypeID;
                fieldAndDataSource.IsMandary = inputField.IsMandary;
                fieldAndDataSource.EnglishName = inputField.EnglishName;
                fieldAndDataSource.ApplicationID = inputField.ApplicationID;
                List<VInputFieldDataSource> vDataSource = TicketBusiness.GetInputDataSourceByFieldID(inputField.Id);
                List<DataSource> dataSourceList = new List<DataSource>();

                if (vDataSource != null && vDataSource.Count > 0)
                {
                    foreach (var data in vDataSource)
                    {
                        DataSource dataSource = new DataSource();
                        dataSource.DataSourceDescription = data.Description;
                        dataSource.DataSourceValue = data.value;
                        dataSourceList.Add(dataSource);
                    }
                }
                if (dataSourceList.Count > 0)
                {
                    fieldAndDataSource.DataSourceList = dataSourceList;
                }
                inputFieldAndDataSourceList.Add(fieldAndDataSource);
            }
            return inputFieldAndDataSourceList;
        }


        #endregion

        public List<VApplication> GetApplicationInfo(long clientID)
        {
            List<VApplication> list = ProjectBusiness.GetApplicationInfo(0, clientID);
            return list;
        }



        [System.Web.Http.HttpGet]
        public string CancelTicket(int ticketID)
        {
            VTicketsRequestInfo ticket = TicketBusiness.GetTicketDetails(ticketID);
            if (ticket.Status != 1)
            {
                TicketBusiness.CancelTicketByID(ticketID);
                return null;
            }
            return "已在处理中";
        }

    }
}

